package com.ysm.smfu.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.ysm.smfu.R;
import com.ysm.smfu.activity.LocationActivity;
import com.ysm.smfu.activity.SearchActivity;
import com.ysm.smfu.activity.ShangHuActivity;
import com.ysm.smfu.adapter.HomeProductAdapter;
import com.ysm.smfu.adapter.MyPagerAdapter;
import com.ysm.smfu.bean.City;
import com.ysm.smfu.bean.HomeProduct;
import com.ysm.smfu.contans.SpKey;
import com.ysm.smfu.protocal.BaseProtocal;
import com.ysm.smfu.protocal.MyStringCallBack;
import com.ysm.smfu.utils.JsonUtil;
import com.ysm.smfu.utils.PrintUtil;
import com.ysm.smfu.utils.UIUtils;
import com.ysm.smfu.view.RefreshLayout;
import com.ysm.smfu.welcome.SharedConfig;
import com.zhy.autolayout.AutoLinearLayout;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2016/9/27.
 */
//public class BendiFragment extends BaseRefreshFragment<HomeSearchResultBean.BusinessInfo> implements View.OnClickListener {
public class BendiFragment extends BaseRefreshFragment<HomeProduct.Goods> implements View.OnClickListener {

    //猜你喜欢...     离我最近..
    private static final String LOCFAIL = "产品推荐";
    private static final String LOCSUCCESS = "产品推荐";
    @BindView(R.id.home_listview)
    ListView homeListview;
    @BindView(R.id.refresh)
    RefreshLayout swipeRefreshLayout;

    private ImageView home_spread_module;
    private SharedPreferences sp;
    private String bdLoc = "";
    private String cityId = "";
    private String lon = "";
    private String lat = "";
    private HomeProductAdapter adapter;
    private AutoLinearLayout fragmentSearchModule;
    private MyReceiver myReceiver;
    private City selectCity;
    private TextView activity_top_text;
    private String selectCity_sp;

    String[] category_name1 = {"精品商城", "兑换券商城", "美食", "美容美发", "浴足", "ktv", "酒店", "聊天"};
    String[] category_name2 = {"兑换点", "加盟商店", "消费俱乐部", "生活在线", "私人定制", "电影", "游戏"};

    int[] category_ims1 = {R.drawable.sc, R.drawable.gwq, R.drawable.ms, R.drawable.mymf, R.drawable.yz,
            R.drawable.ktv, R.drawable.jd, R.drawable.lt};
    int[] category_ims2 = {R.drawable.dhd, R.drawable.jm, R.drawable.xfjlb,
            R.drawable.shzx, R.drawable.srdz, R.drawable.dy, R.drawable.yx};
    String[] category_id1 = {"-1", "-2", "1", "2", "4", "3", "5", "-3"};
    String[] category_id2 = {"8", "6", "0", "0", "0", "7", "0"};
    private ViewPager viewPager;
    private ImageView[] indicators;
    private AutoLinearLayout ovels;
    private TextView text;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = UIUtils.inflate(R.layout.fragment_found_bendi_frag_content);
        ButterKnife.bind(this, view);
        initRefresh(swipeRefreshLayout, true, false);
        addHeadView();
        getCityId();
        return view;
    }

    @Override
    public void load(boolean isLoad) {
        if (isLoad)
            page++;
        getGoodsInfoBySelect(cityId, curCityId);
    }

    private void getCityId() {
        sp = new SharedConfig(UIUtils.getContext()).getCommoneSp();
        cityId = sp.getString(SpKey.SELECID, "");
        curCityId = sp.getString(SpKey.LOCID, "");
        selectCity_sp = sp.getString(SpKey.SELECCITY, "");
        bdLoc = sp.getString(SpKey.BDLOC, "");
        lon = sp.getString(SpKey.LON, "");
        lat = sp.getString(SpKey.LAT, "");
        if (!TextUtils.isEmpty(selectCity_sp)) {
            if (selectCity_sp.endsWith("市"))
                activity_top_text.setText(selectCity_sp.substring(0, selectCity_sp.length() - 1));
            else
                activity_top_text.setText(selectCity_sp);
            text.setText(LOCSUCCESS);
        } else if (!TextUtils.isEmpty(bdLoc)) {
            if (bdLoc.endsWith("市"))
                activity_top_text.setText(bdLoc.substring(0, bdLoc.length() - 1));
            else
                activity_top_text.setText(bdLoc);
            text.setText(LOCSUCCESS);
        } else {
            activity_top_text.setText("定位失败");
            if (text != null)
                text.setText(LOCFAIL);
        }
        getGoodsInfoBySelect(cityId, curCityId);
    }

    /**
     * 为ListView添加头布局
     */
    private void addHeadView() {
        View headView = UIUtils.inflate(R.layout.fragment_found_bendi_frag_head);
        initView(headView);
        /*增加头布局*/
        homeListview.addHeaderView(headView);
        adapter = new HomeProductAdapter(datas, homeListview, this);
        homeListview.setAdapter(adapter);
        registerReceiverForLoc();
    }

    /**
     * 初始化头布局中控件
     *
     * @param headView
     */
    private void initView(View headView) {
//        分类控件
        viewPager = (ViewPager) headView.findViewById(R.id.vp_category);
        ovels = (AutoLinearLayout) headView.findViewById(R.id.ovels);
        text = (TextView) headView.findViewById(R.id.text);
        initIndicators(ovels);

        home_spread_module = (ImageView) headView.findViewById(R.id.home_spread_module);
        fragmentSearchModule = (AutoLinearLayout) headView.findViewById(R.id.fragment_search_module);
        ImageView back = (ImageView) headView.findViewById(R.id.back);
        back.setOnClickListener(this);
        ImageView mainActivity_topbar_img = (ImageView) headView.findViewById(R.id.mainActivity_topbar_img);
        mainActivity_topbar_img.setVisibility(View.GONE);
        TextView titleBody = (TextView) headView.findViewById(R.id.title_body);
        activity_top_text = (TextView) headView.findViewById(R.id.activity_top_text);
        activity_top_text.setVisibility(View.VISIBLE);
        activity_top_text.setOnClickListener(this);
        titleBody.setText("本地服务");
        initListener();
    }

    /**
     * 初始化控件点击
     */
    private void initListener() {
        viewPager.setAdapter(new MyPagerAdapter(category_name1, category_name2, category_ims1, category_ims2, category_id1,
                category_id2, getActivity()));
        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                changeOvel(position);
            }
        });
//        点击事件
        home_spread_module.setOnClickListener(this);
//        搜索点击事件
        fragmentSearchModule.setOnClickListener(this);
    }

    /**
     * 初始化监听
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_top_text:
                UIUtils.startActivity(LocationActivity.class);
                break;
            case R.id.fragment_search_module:
//                跳转到搜索页面
                UIUtils.startActivity(SearchActivity.class);
                break;

            case R.id.home_spread_module:
                if (BaseProtocal.isGoLogin(true, getActivity()))
                    return;
//                跳转到推广页面
                UIUtils.startActivity(ShangHuActivity.class);
                break;

            case R.id.back:
                getActivity().finish();
                break;
        }
    }

    //    当前城市，如果用户没有选择，则为空
    private String curCityId = "";

    /**
     * 通过选择城市来获取最近商家
     *
     * @param cityId
     * @param curCityId
     */
    public void getGoodsInfoBySelect(String cityId, String curCityId) {
        showProduct();
//        BaseProtocal.builder(false).getGoodsInfoBySelect(new MyStringCallBack() {
//            @Override
//            public void onSuccess(String response) {
//                String state = JsonUtil.getState(response);
//                if (TextUtils.equals(state, "1")) {
//                    HomeSearchResultBean homeSearchResultBean = new Gson().fromJson(response, HomeSearchResultBean.class);
//                    List<HomeSearchResultBean.BusinessInfo> currBiList = homeSearchResultBean.biList;
//                    setLoadData(currBiList);

//                    adapter.setDatas(datas);
//                    adapter.notifyDataSetChanged();
//                } else {
//                    onRefreshError();
//                }
//            }
//
//            @Override
//            public void onFail(Exception e) {
//                onRefreshError();
//            }
//        }, cityId, curCityId, lon, lat, page);
    }


    /**
     * 展示产品
     */
    private void showProduct() {
        BaseProtocal.builder(false).getHomeProduct(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("首页产品:" +response);
                String state = JsonUtil.getState(response);
                if (TextUtils.equals(state, "1")) {
                    HomeProduct homeProduct = new Gson().fromJson(response, HomeProduct.class);
                    List<HomeProduct.Goods> goods = homeProduct.goods;
                    setLoadData(goods);

                    adapter.setDatas(datas);
                } else {
                    onRefreshError();
                }
            }

            @Override
            public void onFail(Exception e) {
                onRefreshError();
            }
        }, page);
    }

    /**
     * 注册广播接收位置变化
     */
    private void registerReceiverForLoc() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("loc");
        myReceiver = new MyReceiver();
        getActivity().registerReceiver(myReceiver, intentFilter);
    }

    @Override
    public void refresh() {

    }

    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            selectCity = (City) intent.getSerializableExtra(SpKey.LOC);
            if (selectCity.name.endsWith("市"))
                activity_top_text.setText(selectCity.name.substring(0, selectCity.name.length() - 1));
            else
                activity_top_text.setText(selectCity.name);
            page = 1;
            sp.edit().putString(SpKey.SELECID, selectCity.id).commit();
            sp.edit().putString(SpKey.SELECCITY, selectCity.name).commit();
            cityId = selectCity.id;
//            getGoodsInfoBySelect(selectCity.id, curCityId);
        }
    }

    //    构造指示点
    public void initIndicators(AutoLinearLayout ovels) {
        indicators = new ImageView[2]; // 定义指示器数组大小
        for (int i = 0; i < 2; i++) {
            // 循环加入指示器
            indicators[i] = new ImageView(UIUtils.getContext());
            indicators[i].setBackgroundResource(R.drawable.btn_circle_shape);
            if (i == 0) {
                indicators[i].setBackgroundResource(R.drawable.btn_circle_shape_r);
            }
            //指示点之间到间距
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-2, -2);
            params.leftMargin = UIUtils.dip2px(10);
            ovels.addView(indicators[i], params);
        }
    }

    //    切换指示点
    public void changeOvel(int position) {
        // 更改指示器图片
        for (int i = 0; i < indicators.length; i++) {
            if (position != i)
                indicators[i].setBackgroundResource(R.drawable.btn_circle_shape);
            else
                indicators[position].setBackgroundResource(R.drawable.btn_circle_shape_r);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (myReceiver != null)
            getActivity().unregisterReceiver(myReceiver);
    }
}
